let ws = null;
let intervalId = null;

export const initWebSocket = (url, onMessageCallback) => {
  if (!ws || ws.readyState !== WebSocket.OPEN) {
    ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('WebSocket 连接已建立');
      startHeartbeat(); // 可选：发送心跳包保持连接
    };

    ws.onmessage = (event) => {
      if (onMessageCallback) onMessageCallback(event.data);
    };

    // ws.onclose = () => {
    //   console.log('WebSocket 连接关闭');
    //   clearInterval(intervalId);
    // };

    ws.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };
  }
  return ws;
};

export const sendMessage = (data) => {
  
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(data));
        console.log('WebSocket 发送消息:', data);
    } else {
        console.error('WebSocket 未连接');
    }
};

// 可选：心跳检测防止连接断开
const startHeartbeat = () => {
  intervalId = setInterval(() => {
    sendMessage({ type: 'heartbeat' });
  }, 3000); // 每30秒发送一次心跳
};

export const closeWebSocket = () => {
  if (ws) {
    // ws.close();
    // ws = null;
  }
};